<?php

/**
 * 卓志e仓-花之冠技术对接群
 * author chenshubo
 */
 namespace App\Service\VendorClient\ShopZhuoZhiEc;
use App\Model\PssModel\ServiceConfig;
use Service\AppService\IdService;
use App\Service\BaseService;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use function GuzzleHttp\json_decode;

class ShopZhuoZhiEcApiClient extends BaseService
{
    protected $clientConfig;
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct()
    {
        $this->clientConfig = config('api.shopzhuozhiec');
    }

    /**
     * 创建订单
     */
    public function createOrder( $params = [] )
    {
        $orderInfo      = $params['supplierOrder'];
        $orderItem      = $params['orderGoods'];
        $order          = $params['order'];
        $binfo          = $params['binfo'];


        //支付流水号
        $pay_sn    = $order['paySerial'] ?? $orderInfo['pay_sn'];

        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //优惠
        $discount_money = $orderInfo['discount_money'] < 0 ? - $orderInfo['discount_money'] : $orderInfo['discount_money'] ;

        //支付时间
        $pay_time       = date('Y-m-d H:i:s',$orderInfo['pay_time']);
        //支付流水号
        $order_sn       = $orderInfo['supplier_dsn'];

        //判断支付方式是否存在
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        $payCommanyCode = $apply_extends['payCommanyCode']??'';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode ;
        $pay_value = ServiceConfig::instance()->getConfigByEventsValue('shopzhuozhiec', ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if( empty($pay_value) ) {
            return Normal::returnCode(Normal::FAIL,"支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        }
        

        //组装商品数据列表
        $goodsList          = [];
        $goodsTotalMoney    = 0;
        $way_tax_fee        = 0;
        foreach ($orderItem as $key =>  & $item )
        {
            $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
            $price              = $item['price'];
            $spec_num           = $item['spec_num'];
            $quantity           = $item['quantity'];
            $singlePrice        = bcdiv((string)$price, (string)$spec_num,3);

            //不含税价格
            $goodsPrice         = bcdiv((string)$price, (string)$tax_rate,3);
            $goodsPrice         = bcdiv((string)$goodsPrice, (string)$spec_num,3);
            $goodsPrice         = bcmul((string)$goodsPrice,(string)100,1);
            $goodsPrice         = bcdiv((string)ceil($goodsPrice), 100,2);


            $buyNum             = $spec_num * $quantity;
            $goodsTotalPrice    = bcmul((string)$goodsPrice,(string)$buyNum,2);

            //商品关税当前币种最小单位（分）
            $goodsCustomsTax    = bcsub((string)$singlePrice,(string)$goodsPrice,2);
            $taxAll             = bcmul((string)$goodsCustomsTax,(string)$buyNum,2);

            $goodsInfo = [
                "index"         => ($key+1),
                "goods_id"      => $item['supplier_skucode'],
                //"good_name"     => $item['goods_name'],
                "price"         => (string)$goodsPrice,
                "num"           => $buyNum,
                "dec_total"     => (string)$goodsTotalPrice,
            ];
            $goodsList[] = $goodsInfo;
            $goodsTotalMoney    = bcadd((string)$goodsTotalMoney,(string)$goodsTotalPrice,2);
            $way_tax_fee        = bcadd((string)$way_tax_fee,(string)$taxAll,2);
        }

        //订单总价（商品保税价格 + 运费）
        $totalMoney             = bcadd((string)$goodsTotalMoney, (string)$deliver_money,2);
        $totalMoney             = bcadd((string)$totalMoney, (string)$way_tax_fee,2);
        //订单优惠金额
        $real_total_money       = $orderInfo['real_total_money'];
        $discount_money         = bcsub((string)$totalMoney,(string)$real_total_money,2);
        $currentGoods           = current($orderItem);
        //仓库ID
        $warehouse_id           = $currentGoods['supplier_store_id'];
        //申报方案
        $declare_plan           = $currentGoods['supplier_store_code'];
        //创建订单数据
        $data = [
            "shop_id"                   => $this->clientConfig['SHOP_ID'],
            "order_type"                => $this->clientConfig['order_type'],
            "order_id"                  => $order_sn,
            "created"                   => date("Y-m-d H:i:s",$orderInfo['cd']),
            "modified"                  => date("Y-m-d H:i:s",time()),
            "pay_no"                    => $pay_sn,
            "pay_mode"                  => $pay_value,
            "pay_time"                  => date("Y-m-d H:i:s",time()),
            "change_flag"               => "0",
            "payment"                   => $real_total_money,
            "way_frt_fee"               => $deliver_money,
            "way_frt_fee_cy"            => "CNY",
            "way_ind_fee"               => "0",
            "way_tax_fee"               => $way_tax_fee,
            "discount"                  => $discount_money,
            "warehouse_id"              => $warehouse_id,
            "declare_plan"              => $declare_plan,
            "buyer_reg_no"              => $orderInfo['buyer_realname'],
            "buyer_indentity_type"      => "1",
            "buyer_telephone"           => $orderInfo['buyer_phone'],
            "buyer_identity_card"       => $orderInfo['buyer_idcard'],
            "buyer_name"                => $orderInfo['buyer_realname'],
            "receiver_name"             => $orderInfo['receive_name'],
            "receiver_identity_type"    => "1",
            "receiver_identity_card"    => $orderInfo['buyer_idcard'],
            "receiver_mobile"           => $orderInfo['recveive_phone'],
            "receiver_phone"            => $orderInfo['recveive_phone'],
            "receiver_country"          => "中国",
            "receiver_state"            => $orderInfo['province'],
            "receiver_city"             => $orderInfo['city'],
            "receiver_district"         => $orderInfo['district'],
            "receiver_address"          => $orderInfo['receive_address'],
            "order_goods"               => $goodsList
        ];
        $requestParam = [
            'method'    => 'orderCreate',
            'api_name'  => 'epass.orders.b2c.add',
            'data'      => $data,
        ];
        return $this->execute($requestParam);
    }

    /**
     * 获取sign参数
     */
    private function getSign( $param = [] )
    {
        ksort($param);
        $arr = [];
        foreach ($param as $k=>$v){
            if( is_array($v) ) {
                $v = json_encode($v,JSON_UNESCAPED_UNICODE);
            }
            $arr[] = "{$k}{$v}";
        }
        $str = implode("", $arr);
        $str = str_replace("/", "", $str);
        $str = $this->clientConfig['SECRET_KEY'].$str.$this->clientConfig['SECRET_KEY'];
        return strtoupper(md5($str));
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $method = $param['method'];
        $header = [
            "Content-Type: text/plain;charset=utf-8",
            "Accept:application/json"
        ];

        $data  = $param['data'];
        $data  = array_merge([
            'method'    => $param['api_name'],
            'app_key'   => $this->clientConfig['APP_KEY'],
            'v'         => $this->clientConfig['v'],
            'timestamp' => date("Y-m-d H:i:s"),
        ],$data);
        $data['sign']   = $this->getSign($data);
        $url            = $this->clientConfig['API_DOMAIN'].$this->clientConfig['api_route'][$method];
        $parameter = [
            [
                'tag'       => 'ShopZhuoZhiEc_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'json',
                'header'    => $header,
            ],
        ];
        $resTask    = TaskWorker::instance()->addTask($parameter);
        $resTask    = current($resTask);
        $resHttp    = @json_decode($resTask['response']['result'], true);
        $errorMsg = $resHttp['notes']??'请求失败';
        if( isset($resHttp['status']) && $resHttp['status'] == 1 ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        return Normal::returnCode(Normal::FAIL,$errorMsg);
    }
}
